<template>
  <div class="app-container">
    <el-form
      label-position="right"
      label-width="80px"
      :rules="rules"
      :model="user"
      ref="userForm"
    >
      <el-form-item
        label="状态"
        prop="isBanned"
      >
        <el-radio-group
          v-model="user.isBanned"
          size="medium"
        >
          <el-radio-button :label="0">正常</el-radio-button>
          <el-radio-button :label="1">封禁</el-radio-button>
        </el-radio-group>
      </el-form-item>

      <el-form-item
        label="用户名"
        prop="userName"
      >
        <el-input
          v-model="user.userName"
          clearable
          style="width:300px"
        />
      </el-form-item>

      <el-form-item
        label="密码"
        prop="password"
      >
        <el-input
          v-model="user.password"
          clearable
          show-password
          style="width:300px"
        />
      </el-form-item>

      <el-form-item
        label="手机号"
        prop="phone"
      >
        <el-input
          v-model="user.phone"
          clearable
          style="width:300px"
        />
      </el-form-item>

      <el-form-item
        label="邮箱"
        prop="email"
      >
        <el-input
          v-model="user.email"
          clearable
          style="width:300px"
        />
      </el-form-item>

      <el-form-item label="头像">
        <!-- 头像缩略图 -->
        <pan-thumb :image="user.avatar" />
        <!-- 文件上传按钮 -->
        <el-button
          type="primary"
          icon="el-icon-upload"
          @click="imageCropperShow=true"
        >更换头像</el-button>
        <!-- 
          v-show：是否显示上传组件
          :ki：类似于id，如果一个页面多个图片上传控件，可以
          :url：后台上传的url地址
          @close：关闭上传组件
          @crop-upload-success：上传成功后的回调
        -->
        <image-cropper
          v-show="imageCropperShow"
          :ki="imageCropperKey"
          :url="'/oss/avatar'"
          field="file"
          @close="close"
          @crop-upload-success="cropSuccess"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          :disable="saveBtnDisabled"
          type="primary"
          @click="saveOrUpdate('userForm')"
        >保存</el-button>
        <el-button @click="resetForm('userForm')">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import user from '@/api/user';
import ImageCropper from '@/components/ImageCropper';
import PanThumb from '@/components/PanThumb';

const defaultForm = {
  userName: '',
  password: '',
  phone: '',
  email: '',
  permission: '',
  isBanned: 0,
  avatar: 'http://house-rental-system.oss-cn-beijing.aliyuncs.com/avatar/default.jpg'
};

export default {
  components: { ImageCropper, PanThumb },
  data() {
    return {
      user: {
        userName: '',
        password: '',
        phone: '',
        email: '',
        permission: '',
        isBanned: 0,
        avatar: ''
      },
      saveBtnDisabled: false, // 保存按钮是否禁用
      imageCropperShow: false, // 上传头像组件是否显示
      imageCropperKey: 0, // 上传组件key值
      rules: {
        userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      }
    };
  },
  // 监听
  watch: {
    // 当路由发生变化, 方法执行
    $route(to, from) {
      this.init();
    }
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      // params表示路由中的参数, 指 path: 'edit/:id' 中类似:id的参数
      // 注意是route不是router
      if (this.$route.params && this.$route.params.id) {
        const id = this.$route.params.id;
        this.fetchDataById(id);
      } else {
        // 否则新增一条记录后, defaultForm就变成了之前新增的值
        // 使用对象拓展运算符, 拷贝对象, 而不是引用
        this.user = { ...defaultForm };
      }
    },
    // 通过id获取项目
    fetchDataById(id) {
      user
        .getUserById(id)
        .then(response => {
          this.user = response.data.user;
        })
        .catch(response => {
          this.$message({
            type: 'error',
            message: '获取数据失败'
          });
        });
    },
    // 新建或修改
    saveOrUpdate(formName) {
      this.saveBtnDisabled = true;
      this.$refs[formName].validate(valid => {
        if (valid) {
          // 如果user对象中有userId, 说明是修改, 因为创建不需要输入userId
          // 这个user对象是后端返回给前端的, 不是data中的
          if (this.user.userId) {
            this.updateData();
          } else {
            this.saveData();
          }
        } else {
          console.log('error submit');
          return false;
        }
      });
    },
    // 保存用户
    saveData() {
      user
        .saveUser(this.user)
        .then(response => {
          return this.$message({
            type: 'success',
            message: '保存成功'
          });
        })
        .then(response => {
          // 保存成功跳转到表格页面
          this.$router.push({ path: '/user' });
        })
        .catch(response => {
          this.$message({
            type: 'error',
            message: '保存失败'
          });
        });
    },
    // 修改用户
    updateData() {
      this.saveBtnDisabled = true;
      user
        .updateUser(this.user)
        .then(response => {
          this.$message({
            type: 'success',
            message: '修改成功'
          });
        })
        .then(response => {
          this.$router.push({ path: '/user' });
        })
        .catch(response => {
          this.$message({
            type: 'error',
            message: '保存失败'
          });
        });
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 关闭上传弹窗
    close() {
      this.imageCropperShow = false;
      //上传组件初始化
      this.imageCropperKey = this.imageCropperKey + 1;
    },
    // 上传成功方法
    cropSuccess(data) {
      // 上传之后接口返回图片地址
      this.user.avatar = data.url;
      console.log(this.user.avatar);
      this.close();
    }
  }
};
</script>